<?php

class Navigation {

  protected static $_inst;

  protected function __construct() {

  }

  public static function getInst() {
    if (self::$_inst == NULL) {
      self::$_inst = new self();
    }
    return self::$_inst;
  }

  /**
   * @param   string $navigation
   * @return  array  array of navigation items in conrrection structs
   */
  public static function build($nav_name) {
   
    $sql  = "
      select item.* from core_nav nav
      left join core_nav_item item on(item.nav_id=nav.nav_id)
      where nav.nav_name=? and status= 1
      order by item.ord";

    logger::add($sql);
    logger::add('name: '. $nav_name);

    $items = db::factory()->fetchAll($sql,$nav_name);
    $result = array();
    foreach($items as $item){
      $result[] =  $item;
    }
    return $result;
  }

  public static function buildRescursion($nav_name){
    $sql  = "
      SELECT node.*, (node.rgt - node.lft - 1) as has_child, COUNT(parent.item_id) - 1 AS depth
      FROM core_nav_item AS node,
      core_nav_item AS parent
      WHERE (node.lft BETWEEN parent.lft AND parent.rgt) AND (node.nav_id = parent.nav_id) AND (node.lft > 1) AND (node.nav_id =  (select nav_id from core_nav where nav_name=?))
      GROUP BY node.item_id
      ORDER BY node.lft;
      ;";

    logger::add($sql);
    logger::add('name: '. $nav_name);

    $items = db::factory()->fetchAll($sql,$nav_name);

    return $items;
  }
  /**
   *
   * @param  int $nav_id
   * @return array
   */
  public static function getItemsById($nav_id) {
    $sql = "
      SELECT node.*, (node.rgt - node.lft - 1) as has_child, COUNT(parent.item_id) - 1 AS depth
      FROM core_nav_item AS node,
      core_nav_item AS parent
      WHERE (node.lft BETWEEN parent.lft AND parent.rgt) AND (node.nav_id = parent.nav_id) AND (node.lft > 1) AND (node.nav_id =  (select nav_id from core_nav where nav_name=?))
      GROUP BY node.item_id
      ORDER BY node.lft;
      ;";
    $db = Db::factory();
    return $db->fetchAll($sql, $nav_name);
  }

  /**
   *
   * @param  string $nav_name
   * @return array
   */
  public static function getItemsByName($nav_name) {
    $sql = "
      SELECT node.*, (node.rgt - node.lft - 1) as has_child, COUNT(parent.item_id) - 1 AS depth
      FROM core_nav_item AS node,
      core_nav_item AS parent
      WHERE (node.lft BETWEEN parent.lft AND parent.rgt) AND (node.nav_id = parent.nav_id) AND (node.lft > 1) AND (node.nav_id =  (select nav_id from core_nav where nav_name=?))
      GROUP BY node.item_id
      ORDER BY node.lft;
      ;";
    $db = Db::factory();
    return $db->fetchAll($sql, $nav_name);
  }
}